package com.xianggu.mybatis.utils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author chengjy
 * @date 2025/3/11
 */
public class ObjectTranUtils {

    public static  <T>T MapToObject(Class<T> clazz, Map<String, Object> objectMap){
        Object object = null;
        try {
            Constructor<?> declaredConstructor = clazz.getDeclaredConstructor();
            object = declaredConstructor.newInstance();

            Map<String, Field> fieldMap = Arrays.stream(clazz.getDeclaredFields())
                    .collect(Collectors.toMap(Field::getName, Function.identity(), (f1, f2) -> f2));

            // 遍历map获取对应的属性值
            for (Map.Entry<String, Object> objectEntry : objectMap.entrySet()) {
                String key = objectEntry.getKey();
                Object value = objectEntry.getValue();
                // 判断是否存在该字段

                if(fieldMap.containsKey( key)){
                    Field field = fieldMap.get(key);
                    field.setAccessible(true);
                    field.set( object , value);
                }
            }
            return (T) object;
        } catch (InstantiationException e) {
            throw new RuntimeException("反射异常："+e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("反射异常："+e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("获取无参构造方法："+e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException("无参构造反射异常："+e);
        }
    }
}
